#!/usr/bin/env python
#
#   Changes:
#   - example of usage TreeWalker moved to examples/treewalker1.py
#
__doc__ = ''' Python Flow Control Library, Processes '''
__author__ = 'Andrey Usov <http://devel.ownport.net>'
__meta__ = { 'library': 'pyflowctrl', 'process': 'TreeWalker'}


import os
from pyflowctrl.core4 import WAITING, PROCESSING
from pyflowctrl.core4 import EmptyStream, Stream, Process, Packet

class TreeWalker(Process):
    ''' Tree Walker '''
    def __init__(self):
        ''' __init__  '''
        super(TreeWalker, self).__init__()
        self.input = Stream()
        self.output = Stream()
        
    def __walktree(self, top):
        """ Directory walker """
        try:
            names = os.listdir(top)
        except OSError:
            names = []
        for name in names:
            if os.path.isdir(os.path.join(top, name)):
                for (newtop, children) in self.__walktree(os.path.join(top, name)):
                    yield newtop, children
        yield top, names

    def main(self):
        while True:
            try:
                packet = self.input.get()
            except EmptyStream:
                yield WAITING
                continue
                
            if not os.path.exists(packet.path):
                raise IOError("%s does not exist" % packet.path)
            self.output.put(packet)
            for path, names in self.__walktree(packet.path):
                for name in names:
                    packet.path = os.path.join(path, name)
                    self.output.put(packet)
                    yield PROCESSING

    
